const workRecords = require("../models/workRecords")
const user = require("../models/userDetail")
const fs = require('fs')
const xlsx = require('xlsx')

var express = require('express');
var router = express.Router();
//  知识点标题  题目信息  应作人数  答对人数 正确率  题型
const formidable = require('formidable');

router.post('/', (req, res, next) => {
  var form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    if (err) {
        res.json({ 'state': false })
    } else {
      workRecords.find({
        seq: fields.seq
      }, async(err, docs) => {
        if (err) {
          res.json({ 'state': false, 'msg': err });
        } else{
          // let returnData = {}
          // console.log(docs)
          if(docs.length===0){
            res.json({ 'state': false, 'msg': '暂时没有学生提交作业' });
          }else{
            // let is_exist = () => {
            //   return new Promise(function (resolve, reject) {
            //     let flag = false;
            //     let file_path = './workAnalysis/'+ fields.seq + '_PersonAnalysis.xlsx';
            //     fs.exists(file_path, exists => {
            //       // console.log(exists);
            //       if(exists) {
            //         flag = true;
            //         resolve(flag);
            //       }else {
            //         resolve(flag);
            //       }
            //     })
            //   })
            // }
            let question_num = docs[0].question_answer.length
            // console.log(question_num)
            let stu_list = []
            let xlsx_list = []
            async function find_mes() {
              for(let k=0; k<docs.length; k++) {
                stu_list[k] = {}
                xlsx_list[k] = {}
                stu_list[k].UUID = docs[k].UUID
                let stu = await user.find({
                  UUID: docs[k].UUID
                })
                // console.log(stu)
                stu_list[k].realName = stu[0].realName
                stu_list[k].stuNo = stu[0].stuNo
                stu_list[k].question_num = question_num
                stu_list[k].right = 0
                xlsx_list[k]['学生姓名'] = stu[0].realName
                xlsx_list[k]['学生学号'] = stu[0].stuNo
                xlsx_list[k]['学生答题数'] = question_num
                xlsx_list[k].right = 0
                docs[k].question_answer.forEach((e, index) => {
                  let num = index+1
                  let name = num + '号题目答题结果'; 
                  let answer_name = num + '号题目回答内容';
                  xlsx_list[k][answer_name] = e.stu_answer.sort().toString();
                  if(e.result) {
                    xlsx_list[k][name] = 1
                    stu_list[k].right++
                    xlsx_list[k].right++
                  }else{
                    xlsx_list[k][name] = 0
                  }
                })
                stu_list[k].percent = `${parseFloat((stu_list[k].right/question_num*100).toFixed(2))}%` 
                xlsx_list[k]['正确率'] = `${parseFloat((xlsx_list[k].right/question_num*100).toFixed(2))}%` 
              }
              let buffer = xlsx.utils.json_to_sheet(xlsx_list);
              let key = Object.keys(buffer).sort();
              let ref = key[1] + ':' + key[key.length-1];
              let workbook = {
                SheetNames: ['sheetname'],
                Sheets: {
                  'sheetname': Object.assign({}, buffer, {'!ref': ref})
                },
              }
              xlsx.writeFile(workbook, './workAnalysis/' + fields.seq + '_PersonAnalysis.xlsx');
              return stu_list
            }
            find_mes().then(result => {
              res.json({ 'state': true, 'data': result });
            })
          }
        }
      })
    }
  })
})

module.exports = router;